<!-- CustomSelect.vue -->
<template>
	<view class="custom-select-container">
		<!-- 下拉框主体 -->
		<view class="custom-select" ref="selectRef">
			<view class="selected-option">
				<image src="@/static/icons/add515151.png" mode="aspectFit"
					style="width: 26px; height: 26px; padding: 0 10rpx" @tap="toggleDropdown">
				</image>
			</view>
			<view v-if="isDropdownOpen" class="options-list">
				<view v-for="(option, index) in options" :key="index" class="option-item" @click="selectOption(option)">
					{{ option.name }}
				</view>
			</view>
		</view>

		<!-- 蒙版 -->
		<view v-if="isDropdownOpen" :class="showMask ? 'mask' : 'hideMark'" @click="closeDropdown"></view>
	</view>
</template>

<script setup>
	import {
		ref,
		watch,
		onMounted,
		onUnmounted,
		getCurrentInstance
	} from "vue";
	const props = defineProps({
		options: {
			type: Array,
			required: true,
		},
		showMask: {
			type: Boolean,
			default: true,
		},
	});

	const emit = defineEmits([
		"update:modelValue",
		"open",
		"close",
		"change",
		"scanTrue",
	]);

	const isDropdownOpen = ref(false);
	const selectedOption = ref("");
	const selectRef = ref(null);
	const instance = getCurrentInstance();
	const hasPermission = ref(false);
	const openId = ref("");

	// 检查是否在小程序环境
	const isMiniProgram = () => {
		try {
			return uni.getSystemInfoSync().platform !== "devtools";
		} catch (e) {
			return false;
		}
	};

	const toggleDropdown = () => {
		isDropdownOpen.value = !isDropdownOpen.value;
		emit(isDropdownOpen.value ? "open" : "close");
	};
	// 处理扫码结果
	const handleScanResult = (result) => {
		if (result) {
			const encodedUid = encodeURIComponent(result);
			uni.navigateTo({
				url: `/Device/AddManually/AddManually?uid=${encodedUid}&&isQr=true`,
			});
		}
	};
	const selectOption = async (option) => {
		openId.value = uni.getStorageSync("openid") || false;
		if (!openId.value) {
			isDropdownOpen.value = false;
			uni.showModal({
				content: "此功能需要登录后方可添加设备,是否登录?",
				success: function(res) {
					if (res.confirm) {
						uni.navigateTo({
							url: "/pages/login/login",
						});
					} else if (res.cancel) {
						console.log("用户点击取消");
					}
				},
			});
			return;
		}
		selectedOption.value = option.name;
		isDropdownOpen.value = false;
		emit("update:modelValue", option.id);
		emit("change", option);
		emit("close");
		if (option.id == "1") {
			uni.navigateTo({
				url: "/Device/addDevice/addDevice",
			});
		}
		if (option.id == "2") {
			try {
				const res = await uni.getSetting();
				if (res.authSetting["scope.camera"]) {
					uni.scanCode({
						onlyFromCamera: false, // 只允许相机扫码
						autoZoom: true,
						scanType: ["qrCode"],
						success: (res) => {
							handleScanResult(res.result);
						},
						fail: (err) => {
							console.error("扫码失败:", err);
							uni.showToast({
								title: "扫码失败",
								icon: "none",
							});
						},
					});
				} else {
					// 自动请求权限
					await requestCameraPermissionAndScan();
				}
			} catch (err) {
				uni.showToast({
					title: "权限检查失败",
					icon: "none",
				});
			}
		}
	};

	const requestCameraPermissionAndScan = async () => {
		try {
			await uni.authorize({
				scope: "scope.camera",
			});
			// 权限获取成功后直接调用扫码
			uni.scanCode({
				onlyFromCamera: false,
				autoZoom: true,
				scanType: ["qrCode", "pdf417", "datamatrix", "barCode"],
				autoDecodeCharset: true,
				success: (res) => {
					handleScanResult(res.result);
				},
			});
		} catch (err) {
			uni.showModal({
				title: "权限提示",
				content: "需要相机权限才能使用扫码功能，是否前往设置开启？",
				confirmText: "去设置",
				success: (res) => {
					if (res.confirm) {
						uni.openSetting();
					}
				},
			});
		}
	};

	const closeDropdown = () => {
		if (isDropdownOpen.value) {
			isDropdownOpen.value = false;
			emit("close");
		}
	};

	// 处理点击外部关闭下拉框
	const handleGlobalClick = (event) => {
		if (!isDropdownOpen.value) return;

		// 使用更安全的方式获取元素位置
		selectRef.value?.$el
			?.boundingClientRect((rect) => {
				if (!rect) return;

				// 获取触摸/点击位置
				const clientX = event.touches?.[0]?.clientX || event.clientX;
				const clientY = event.touches?.[0]?.clientY || event.clientY;

				if (clientX && clientY) {
					// 判断是否点击在组件外部
					if (
						clientX < rect.left ||
						clientX > rect.right ||
						clientY < rect.top ||
						clientY > rect.bottom
					) {
						closeDropdown();
					}
				}
			})
			.exec();
	};

	// 事件监听注册和注销
	const registerGlobalEvents = () => {
		if (isMiniProgram()) {
			// 小程序环境
			uni.$on("globalTouchEnd", handleGlobalClick);
		} else {
			// H5环境
			// #ifdef H5
			document.addEventListener("click", handleGlobalClick);
			// #endif
		}
	};

	const unregisterGlobalEvents = () => {
		if (isMiniProgram()) {
			uni.$off("globalTouchEnd", handleGlobalClick);
		} else {
			// #ifdef H5
			document.removeEventListener("click", handleGlobalClick);
			// #endif
		}
	};

	// 页面加载时初始化
	onMounted(() => {
		// 注册全局事件监听
		registerGlobalEvents();

		// 监听下拉框状态变化
		watch(isDropdownOpen, (val) => {
			if (val) {
				// 如果是小程序环境且显示了蒙版，在蒙版上添加touch事件
				if (isMiniProgram() && props.showMask) {
					// 延迟执行确保DOM已更新
					setTimeout(() => {
						selectRef.value?.$el?.nextSibling?.addEventListener(
							"touchend",
							handleGlobalClick
						);
					}, 0);
				}
			} else {
				// 下拉框关闭时，移除可能添加的touch事件
				if (isMiniProgram() && props.showMask) {
					selectRef.value?.$el?.nextSibling?.removeEventListener(
						"touchend",
						handleGlobalClick
					);
				}
			}
		});
	});

	// 组件卸载时清理
	onUnmounted(() => {
		// 移除全局事件监听
		unregisterGlobalEvents();

		// 确保移除可能添加的touch事件
		if (isMiniProgram() && props.showMask) {
			selectRef.value?.$el?.nextSibling?.removeEventListener(
				"touchend",
				handleGlobalClick
			);
		}
	});
</script>

<style scoped>
	/* 样式保持不变 */
	.custom-select-container {
		position: relative;
		display: inline-block;
		/* 添加以下两行 */
		-webkit-tap-highlight-color: transparent;
		tap-highlight-color: transparent;
	}

	.custom-select {
		position: relative;
		cursor: pointer;
		/* 添加以下两行 */
		-webkit-tap-highlight-color: transparent;
		tap-highlight-color: transparent;
	}

	.selected-option {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.options-list {
		position: absolute;
		top: 120%;
		right: 10rpx;
		border: 1px solid #ccc;
		border-top: none;
		background-color: #fff;
		width: 200rpx;
		z-index: 1000;
		border-radius: 20rpx;
		/* 添加阴影过渡 */
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
	}

	.option-item {
		padding: 10px;
		/* 添加以下样式 */
		-webkit-tap-highlight-color: transparent;
		transition: background-color 0.15s ease;
		user-select: none;
	}

	.option-item:active {
		background-color: transparent;
	}

	.mask,
	.hideMark {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;
		/* 添加过渡效果 */
		transition: background-color 0.3s ease;
	}

	.mask {
		background-color: rgba(0, 0, 0, 0.2);
	}

	.hideMark {
		background-color: rgba(0, 0, 0, 0);
	}
</style>